package GUI;

import edu.hitsz.application.Main;
import edu.hitsz.data.ScoreDataDAO;
import edu.hitsz.data.ScoreDataImpl;
import edu.hitsz.data.ScoreObj;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

/**
 * @author CsCN
 */
public class ScorePanel {
    private JPanel scorePanel;
    private JButton deleteButton;
    private JPanel buttonPanel;
    private JPanel labelPanel;
    private JPanel tablePanel;
    private JScrollPane scrollPane;
    private JTable scoreTable;
    private JLabel tableHeadLabel;
    private JLabel modeLabel;
    private static ScoreDataDAO scoreData;


    public ScorePanel() {
        String gameModeStr = Main.gameMode.toString();
        scoreData = new ScoreDataImpl(gameModeStr);
        modeLabel.setText("难度: " + gameModeStr);
        deleteButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int choice = JOptionPane.showConfirmDialog(null,"是否确定删除选中的玩家？");
                if (choice == JOptionPane.OK_OPTION) {
                    int index = scoreTable.getSelectedRow();
                    if (index != -1) {
                        deleteRecord(index);
                    }
                }
            }
        });
        updateTable();
    }

    public JPanel getPanel() {
        return scorePanel;
    }

    public void addRecord(ScoreObj scoreObj){
        scoreData.doAdd(scoreObj);
        scoreData.toFile();
        updateTable();
    }

    public void deleteRecord(int index){
        scoreData.deleteByIndex(index);
        scoreData.toFile();
        updateTable();
    }

    public void updateTable() {
        String[] columnName = {"名次", "玩家名", "得分", "记录时间"};
        DefaultTableModel tableModel = new DefaultTableModel(getScoreDataVector(), columnName){
            @Override
            public boolean isCellEditable(int row, int col) {
                return false;
            }
        };
        scoreTable.setModel(tableModel);
        scrollPane.setViewportView(scoreTable);
    }

    private String[][] getScoreDataVector() {
        List<ScoreObj> scoreList = scoreData.getAllData();
        String[][] ret = new String[scoreList.size()][4];
        int i = 0;
        for (ScoreObj score : scoreList) {
            ret[i][0] = Integer.toString(i + 1);
            ret[i][1] = score.getUserName();
            ret[i][2] = Integer.toString(score.getScore());
            ret[i][3] = score.getTime();
            i++;
        }
        return ret;
    }
}
